package com.gagakuai.type;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/*
 * @program: common-starters
 * @description: 参数的范型
 * @author: houhong
 * @create: 2023-06-30 21:58
 */
public abstract class TypeReference<T> {


    private final Type rawType;

    protected TypeReference() {
        rawType = getSuperclassTypeParameter(getClass());
    }


    private Type getSuperclassTypeParameter(Class<?> clazz) {
        //获取父类的范型类型
        Type genericSuperclass = clazz.getGenericSuperclass();

        if (genericSuperclass instanceof Class) {
            if (TypeReference.class != genericSuperclass) {
                return getSuperclassTypeParameter(clazz.getSuperclass());
            }
            throw new TypeException("'" + getClass() + "' extends TypeReference but misses the type parameter. "
                    + "Remove the extension or add a type parameter to it.");
        }

        Type rawType = ((ParameterizedType) genericSuperclass).getActualTypeArguments()[0];
        if (rawType instanceof ParameterizedType) {
            rawType = ((ParameterizedType) rawType).getRawType();
        }
        return rawType;
        
    }

}